package com.compty.paint.manager;

import java.util.ArrayList;
import java.util.List;

import com.compty.core.hibernate.HibernateEntityDao;
import com.compty.core.utils.CommonsUtil;
import com.compty.paint.domain.CustomerInfo;
import com.compty.paint.util.Constants;
import com.compty.security.domain.UserState;

public class CustomerInfoManager  extends HibernateEntityDao<CustomerInfo>{
	
	 /**
     * -1： 用户不存在   1:成功 2：密码不正确  3:用户状态不正常
     */
	@SuppressWarnings("unchecked")
	public List login(String username, String password) {
		
		List list = new ArrayList();
		
		List<CustomerInfo> userlist = super.findBy("userName",username);
		if (userlist == null || userlist.size() == 0) {
			list.add(-1);
			return list;
		}
		
		Object[]  returnArray = checkPwd(userlist,password);
		String flag = (String) returnArray[0];
		if(!"1".equals(flag)){
			list.add(Integer.valueOf(flag));
			return list;
		}
		else{
			CustomerInfo customer = (CustomerInfo) returnArray[1];
			list.add(1);
			list.add(customer);
		}
		
		return list;
	}
	
	/********** 检查用户密码  **************/
	private Object[] checkPwd(List<CustomerInfo> userlist, String password){
		
		Object[] array = new Object[2];
		
		String flag = "2";
		for (int i = 0; i < userlist.size(); i++) {
			CustomerInfo customer = userlist.get(i);
			UserState userState =customer.getUserState();
			if(userState != null && (Constants.User_State_Normal).equals(userState.getEnglish_name())){
				if(customer.getPasswd().equals(CommonsUtil.getMD5(password))){
					flag = "1";
					array[0] = flag;
					array[1] = customer;
					return array;
				}
			}else{
				flag = "3";
			}
		}
		
		array[0] = flag;
		
		return array;
	}
	
	/**
	 * 由用户名查找用户
	 * @param userName 用户名
	 */
	@SuppressWarnings("unchecked")
	public CustomerInfo findByName(String userName){
		String hql = "from CustomerInfo where userName=? order by id desc";
		List<CustomerInfo> userlist = super.find(hql, userName);
		if (userlist != null && userlist.size() > 0) {
			return userlist.get(0);
		}
		return null;
	}
	
	/*** 充值预存款  ***/
	public void addMoney(Long memberid, Double num) {
		CustomerInfo customerInfo = this.get(memberid);
		Double advance = customerInfo.getAdvance();
		advance = advance+ num;
		super.save(customerInfo);
	}

	/*** 消费预存款 ***/
	public void cutMoney(Long memberid, Double num) {
		CustomerInfo member  = this.get(memberid);	
		if(member.getAdvance()<num){
			throw new  RuntimeException("预存款不足:需要["+num+"],剩余["+member.getAdvance()+"]");
		}
		Double advance = member.getAdvance();
		advance = advance -  num;
		super.save(member);
	}

}
